from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler
from rest_framework.response import Response

class MagBaseException(APIException):
    code = 10000 # 0表示成功，非0 表示失败
    message = "未知异常，请联系管理员"

    @classmethod # class instance
    def get_message(cls):
        return {'code': cls.code, 'message': cls.message}

class NotFound(MagBaseException):
    code = 1000 # js中识别编号
    message = '找不到数据'

class ValidationError(MagBaseException):
    code = 1001
    message = "提交的数据有误，请检查"

class InvalidPassword(MagBaseException):
    code = 1002
    message = "密码验证失败"

class InvalidUsernameOrPassword(MagBaseException):
    code = 1
    message = "用户名或密码错误，请重新登录"

class NotAuthenticated(MagBaseException):
    code = 2
    message = "没有登录过，请先登录"

class InvalidToken(MagBaseException):
    code = 5
    message = "登录无效，请重新登录"

exc_map = {
    # 'DRF异常名': 异常类
    # 'DoesNotExist': NotFound
    "InvalidToken": InvalidToken,
    "AuthenticationFailed": InvalidUsernameOrPassword,
    "NotAuthenticated": NotAuthenticated,
    "ValidationError": ValidationError,
    "InvalidPassword": InvalidPassword
}

def global_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    # 说明一定有异常
    response = exception_handler(exc, context)
    print('+' * 30)
    print(exc, type(exc), '###############')
    print(response, '++++++++++++')
    # log
    if isinstance(exc, MagBaseException):
        message = exc.get_message()
    else:
        message = exc_map.get(exc.__class__.__name__, MagBaseException).get_message()
    return Response(message, status=200) # 200成功回调，400失败回调


